﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Security.Principal;
using System.Web.Mvc;
using Kratos.Framework.ContentManagement.Models.Order;

namespace Kratos.Framework.ContentManagement.Models
{
    public class UserInfo : IPrincipal
    {
        public UserInfo()
        {
            _orders = new List<Orders>();
        }

        [HiddenInput(DisplayValue = false)]
        [ScaffoldColumn(false)]
        public virtual int Id { get; set; }

        [Required(ErrorMessage = "必须字段")]
        [Remote("ValidateUser", "Account", ErrorMessage = "用户账号已存在", HttpMethod = "POST")]
        public virtual string UserId { get; set; }

        [Required(ErrorMessage = "必须字段")]
        [UIHint("Password")]
        public virtual string Password { get; set; }

        [HiddenInput(DisplayValue = false)]
        public virtual DateTime? CreateTime { get; set; }

        [HiddenInput(DisplayValue = false)]
        public virtual DateTime? LastLogOnTime { get; set; }

        private IList<Orders> _orders;
        public virtual IEnumerable<Orders> Orders
        {
            get
            {
                return _orders;
            }
        }

        public virtual IIdentity Identity
        {
            get
            {
                bool isAuthenticated = Id > 0 && UserId.Trim() != "";
                return new Identity(isAuthenticated, UserId);
            }
        }

        public virtual IEnumerable<ActionPermission> ActionPermissions { get; set; }

        /// <summary>
        /// 暂时不需要角色
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public virtual bool IsInRole(string role)
        {
            return true;
        }

        #region 公有方法

        public virtual void AddOrder(Orders order)
        {
            order.User = this;
            _orders.Add(order);
        }

        #endregion
    }

    /// <summary>
    /// 用户标识
    /// </summary>
    public class Identity : IIdentity
    {
        private readonly bool _isAuthenticated;
        private readonly string _name;

        public Identity(bool isAuthenticated, string name)
        {
            _isAuthenticated = isAuthenticated;
            _name = name;
        }

        public string AuthenticationType
        {
            get { return "Forms"; }
        }

        public bool IsAuthenticated
        {
            get { return _isAuthenticated; }
        }

        public string Name
        {
            get { return _name; }
        }
    }
}
